import {
  reqAddHospitalSet,
  reqGetHospitalSetById,
  reqUpdateHospitalSet,
} from "@/api/hospital/hospitalSet";
import { Button, Card, Checkbox, Form, Input, message, Space } from "antd";
import React, { useEffect, useState } from "react";
import { useNavigate, useParams } from "react-router-dom";

export default function AddOrUpdateHospital() {
  //获得 form 对象
  let [form] = Form.useForm();
  //声明 loading 状态
  let [loading, setLoading] = useState(false);
  //获得 navigate 函数
  let navigate = useNavigate();

  //表单完成的事件回调
  let finish = async () => {
    try {
      //获取表单数据
      let fields = form.getFieldsValue();
      //设置为 加载中
      setLoading(true);
      //如果 url 中没有 id 参数, 则新增数据
      if (!id) {
        //发送请求
        await reqAddHospitalSet(fields);
        //提示成功
        message.success("添加成功");
      } else {
        //如果url中存在 id 参数, 则更新数据
        await reqUpdateHospitalSet({...fields, id});
        //提示成功
        message.success("修改成功");
      }
      setLoading(false);
    } catch (e) {
      setLoading(false);
    }
  };

  let goBack = () => {
    navigate("/syt/hospital/hospitalSet");
  };

  //获取 id 参数
  let { id } = useParams();

  //获取当前 id 的医院设置信息
  useEffect(() => {
    let getHospital = async () => {
      //发送请求
      let hospital = await reqGetHospitalSetById(id as string);
      //修改 form 表单元素的值
      form.setFieldsValue(hospital);
    };
    getHospital();
  }, []);

  return (
    <Card>
      <Form
        form={form}
        labelCol={{ span: 3 }}
        wrapperCol={{ span: 21 }}
        onFinish={finish}
      >
        <Form.Item
          label="医院名称"
          name="hosname"
          rules={[{ required: true, message: "医院名称不能为空" }]}
        >
          <Input />
        </Form.Item>

        <Form.Item
          label="医院编号"
          name="hoscode"
          rules={[{ required: true, message: "医院编号不能为空" }]}
        >
          <Input />
        </Form.Item>

        <Form.Item
          label="API 基础路径"
          name="apiUrl"
          rules={[{ required: true, message: "基础路径不能为空" }]}
        >
          <Input />
        </Form.Item>

        <Form.Item
          label="联系人姓名"
          name="contactsName"
          rules={[{ required: true, message: "联系人姓名不能为空" }]}
        >
          <Input />
        </Form.Item>

        <Form.Item
          label="联系人手机号"
          name="contactsPhone"
          rules={[
            { required: true, message: "联系人手机号不能为空" },
            {
              pattern: /^1\d{10}$/,
              message: "手机号格式不正确",
            },
          ]}
        >
          <Input />
        </Form.Item>

        <Form.Item wrapperCol={{ offset: 3, span: 16 }}>
          <Space>
            <Button loading={loading} type="primary" htmlType="submit">
              保存
            </Button>
            <Button onClick={goBack}>返回</Button>
          </Space>
        </Form.Item>
      </Form>
    </Card>
  );
}
